import React, { useState, useEffect } from 'react';
import { 
  Layout, Typography, List, Button, InputNumber, Card, 
  Tag, Divider, Checkbox, Row, Col, Space, Empty, Spin,
  Breadcrumb, message
} from 'antd';
import { Link, useNavigate } from 'react-router-dom';
import { DeleteOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

// 模拟购物车数据
const mockCartItems = [
  {
    id: 1,
    productId: 1,
    name: 'iPhone 13 Pro',
    price: 6999,
    originalPrice: 7999,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLe2mALDSVAAF0enjwEQA837.jpg',
    quantity: 1,
    stock: 50,
    selected: true,
    isSecKill: true,
    secKillEndTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 2,
    productId: 6,
    name: 'Switch游戏机',
    price: 1799,
    originalPrice: 2099,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLeviAFdHhAAErLFJZZsg037.jpg',
    quantity: 1,
    stock: 100,
    selected: true,
    isSecKill: true,
    secKillEndTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 3,
    productId: 2,
    name: '蓝牙耳机',
    price: 299,
    originalPrice: 299,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/A3/wKj0iWTRBW-ARRIuAAG1qClJfLY822.jpg',
    quantity: 2,
    stock: 200,
    selected: true,
    isSecKill: false,
    secKillEndTime: null
  }
];

const CartPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [cartItems, setCartItems] = useState<any[]>([]);
  const [selectAll, setSelectAll] = useState(true);

  useEffect(() => {
    // 模拟数据加载
    setLoading(true);
    setTimeout(() => {
      setCartItems(mockCartItems);
      setLoading(false);
    }, 500);
  }, []);

  const handleQuantityChange = (id: number, value: number | null) => {
    if (!value) return;
    
    setCartItems(items => 
      items.map(item => 
        item.id === id ? { ...item, quantity: value } : item
      )
    );
  };

  const handleRemoveItem = (id: number) => {
    setCartItems(items => items.filter(item => item.id !== id));
    message.success('已从购物车移除');
  };

  const handleSelectItem = (id: number, checked: boolean) => {
    const newItems = cartItems.map(item => 
      item.id === id ? { ...item, selected: checked } : item
    );
    
    setCartItems(newItems);
    setSelectAll(newItems.every(item => item.selected));
  };

  const handleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    setCartItems(items => 
      items.map(item => ({ ...item, selected: checked }))
    );
  };

  const getTotalPrice = () => {
    return cartItems
      .filter(item => item.selected)
      .reduce((sum, item) => sum + item.price * item.quantity, 0);
  };

  const getTotalSaved = () => {
    return cartItems
      .filter(item => item.selected)
      .reduce((sum, item) => sum + (item.originalPrice - item.price) * item.quantity, 0);
  };

  const getSelectedCount = () => {
    return cartItems.filter(item => item.selected).length;
  };

  const handleCheckout = () => {
    if (getSelectedCount() === 0) {
      message.warning('请至少选择一件商品');
      return;
    }
    
    message.success('正在前往结算...');
    // 实际项目中应该跳转到结算页面
    // navigate('/checkout');
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className="cart-page">
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>购物车</Breadcrumb.Item>
      </Breadcrumb>
      
      <Title level={2}>我的购物车</Title>
      
      {cartItems.length > 0 ? (
        <>
          <Card style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', padding: '0 16px' }}>
              <Checkbox 
                checked={selectAll} 
                onChange={e => handleSelectAll(e.target.checked)}
                style={{ marginRight: 8 }}
              />
              <Text strong style={{ flex: 1 }}>全选</Text>
              <Text style={{ width: 100, textAlign: 'center' }}>单价</Text>
              <Text style={{ width: 120, textAlign: 'center' }}>数量</Text>
              <Text style={{ width: 100, textAlign: 'center' }}>小计</Text>
              <Text style={{ width: 60, textAlign: 'center' }}>操作</Text>
            </div>
          </Card>
          
          <List
            itemLayout="horizontal"
            dataSource={cartItems}
            renderItem={item => (
              <Card style={{ marginBottom: 8 }}>
                <List.Item>
                  <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                    <Checkbox 
                      checked={item.selected} 
                      onChange={e => handleSelectItem(item.id, e.target.checked)}
                      style={{ marginRight: 8 }}
                    />
                    
                    <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                      <img 
                        src={item.imageUrl} 
                        alt={item.name} 
                        style={{ width: 80, height: 80, marginRight: 16 }}
                      />
                      <div>
                        <Link to={`/products/${item.productId}`}>
                          <Text strong>{item.name}</Text>
                        </Link>
                        {item.isSecKill && (
                          <Tag color="red" style={{ marginLeft: 8 }}>秒杀</Tag>
                        )}
                      </div>
                    </div>
                    
                    <div style={{ width: 100, textAlign: 'center' }}>
                      <Text type="danger">¥{item.price}</Text>
                      {item.originalPrice > item.price && (
                        <div>
                          <Text delete type="secondary" style={{ fontSize: 12 }}>
                            ¥{item.originalPrice}
                          </Text>
                        </div>
                      )}
                    </div>
                    
                    <div style={{ width: 120, textAlign: 'center' }}>
                      <InputNumber 
                        min={1} 
                        max={item.stock} 
                        value={item.quantity}
                        onChange={value => handleQuantityChange(item.id, value)}
                      />
                    </div>
                    
                    <div style={{ width: 100, textAlign: 'center' }}>
                      <Text type="danger">¥{(item.price * item.quantity).toFixed(2)}</Text>
                    </div>
                    
                    <div style={{ width: 60, textAlign: 'center' }}>
                      <Button 
                        type="text" 
                        danger
                        icon={<DeleteOutlined />} 
                        onClick={() => handleRemoveItem(item.id)}
                      />
                    </div>
                  </div>
                </List.Item>
              </Card>
            )}
          />
          
          <Card>
            <Row justify="end" align="middle" gutter={16}>
              <Col>
                <Space>
                  <Text>已选商品 {getSelectedCount()} 件</Text>
                  <Text>合计: <span style={{ color: '#ff4d4f', fontSize: 18, fontWeight: 'bold' }}>¥{getTotalPrice().toFixed(2)}</span></Text>
                  {getTotalSaved() > 0 && (
                    <Text type="secondary">已节省: ¥{getTotalSaved().toFixed(2)}</Text>
                  )}
                </Space>
              </Col>
              <Col>
                <Button type="primary" size="large" onClick={handleCheckout}>
                  去结算
                </Button>
              </Col>
            </Row>
          </Card>
        </>
      ) : (
        <Card>
          <Empty
            description="购物车空空如也"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Button type="primary">
              <Link to="/products">去购物</Link>
            </Button>
          </Empty>
        </Card>
      )}
    </div>
  );
};

export default CartPage; 